package com.example.springbootjwt.controller;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JwtController {
    private final String secretKey = "私有秘钥";

    @RequestMapping("/create")
    public String create(String name) {
        if (!StringUtils.hasLength(name)) {
            return "fail";
        }
        // 签名（私钥+某算法）
        Algorithm sign = Algorithm.HMAC256(secretKey);
        String authCode = JWT.create()
                .withClaim("name", name) // 加密数据
//                .withExpiresAt(Instant.now().plusSeconds(30 * 60)) // 过期时间
                .sign(sign); // 设置签名
        return authCode;
    }

    @RequestMapping("/decode")
    public String decode(String authCode) {
        // JWT 解码对象（接收验证结果，如果签名正确且未过期得到此对象，反之此对象为 null）
        DecodedJWT decodedJWT = null;
        try {
            Algorithm algorithm = Algorithm.HMAC256(secretKey); // 签名（私钥+某算法）
            JWTVerifier verifier = JWT.require(algorithm).build(); // 创建验证对象
            decodedJWT = verifier.verify(authCode); // 执行验证
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (JWTVerificationException e) {
            e.printStackTrace();
        }
        if (decodedJWT == null) { // 验证失败
            return "参数无效";
        }
        return decodedJWT.getClaim("name").asString();
    }
}
